﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Validate_Solution
{
    internal class TextValidater : UIValidater
    {
        private bool isRequired;
        private string regularExpression;
        private Control control;
        private string requiredErrorMessage;
        private string regexErrorMessage;

        public TextValidater(bool isRequired, string regularExpression, Control control, string requiredErrorMessage,               string regexErrorMessage)
        {
            this.isRequired = isRequired;
            this.regularExpression = regularExpression;
            this.control = control;
            this.requiredErrorMessage = requiredErrorMessage;
            this.regexErrorMessage = regexErrorMessage;
        }

        public bool IsRequired
        {
            get { return isRequired; }
            set { isRequired = value; }
        }

        public string RegularExpression
        {
            get { return regularExpression; }
            set { regularExpression = value; }
        }

        public Control Control
        {
            get { return control; }
            set { control = value; }
        }

        public override bool Validate(out string errorMessage, out Control[] errorControls)
        {
            errorMessage = null;
            errorControls = null;
            if (control.Text == string.Empty)
            {
                if (isRequired)
                {
                    errorMessage = requiredErrorMessage;
                    errorControls = new Control[] { this.control };
                    return false;
                }
                else
                {
                    return true;
                }
            }
            if (regularExpression != null)
            {
                Regex regex = new Regex(regularExpression);
                if (!regex.IsMatch(control.Text))
                {
                    errorMessage = regexErrorMessage;
                    errorControls = new Control[] { this.control };
                    return false;
                }
            }
            return true;
        }
    }
}
